package com.mini.demos.webgame;

import java.net.InetSocketAddress;

import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.mini.demos.webgame.codec.GameCodecFactory;
import com.mini.demos.webgame.handler.GameHandlerFactory;
import com.mini.demos.webgame.msg.JobMsg;
import com.mini.demos.webgame.msg.MsgHead;
import com.mini.demos.webgame.util.CommandConstants;
import com.mini.demos.webgame.util.MsgSequenceId;
import com.mini.framework.communicate.mina.adapter.MsgHandlerAdapter;
import com.mini.framework.communicate.mina.protocol.ProtocolCodeFactory;

public class Client {

	public static void main(String arg[]) {
		NioSocketConnector connector = new NioSocketConnector();

		connector.getFilterChain().addLast("codec",new ProtocolCodecFilter(new ProtocolCodeFactory(new GameCodecFactory())));

		connector.getFilterChain().addLast("logger", new LoggingFilter());

		IoHandler handler = new MsgHandlerAdapter(new GameHandlerFactory());
		connector.setHandler(handler);

		IoSession session;
		for (int i=1;i<=100000;i++) {
			try {
				ConnectFuture future = connector.connect(new InetSocketAddress(
						"127.0.0.1", 2010));
				future.awaitUninterruptibly();
				session = future.getSession();
				JobMsg msg = new JobMsg();
				MsgHead head = new MsgHead();
				head.setVersion((byte)0x01);
				head.setCommandId(CommandConstants.JOB);
				head.setSeqId(i);
				head.setTotalLength(100);
				head.setTime(1000);
				head.setSpace(0);
				msg.setHead(head);
				msg.setJobId(i);
				msg.setJobType(1);
				msg.setCostPrice(100);
				msg.setCostTime(1);
				msg.setGetPrice(200);
				msg.setUserName("jason");
				session.write(msg);
				//break;
			} catch (RuntimeIoException e) {
				System.err.println("Failed to connect.");
				e.printStackTrace();
				try {
					Thread.sleep(5000);
				} catch (Exception ee) {
					ee.printStackTrace();
				}
			}
		}
		//session.getCloseFuture().awaitUninterruptibly();

		connector.dispose();

	}

}
